<!--goodsPay 商品支付 -->
<template>
  <yy-page class="p goods-pay">
    <!-- <view class="goodsPay pageBgColor flex-"> -->
    <view class="flex-1 goods-pay__inner">
      <view class="border-radius-18 goods">
        <view class="top">
          <product-item class="pb15" :src="imageUrl" :info="info" :show-buy="false" width="134rpx" height="134rpx" />
        </view>
        <view class="zm-bor-t tip-box flex flex-w bottom">
          <view class="flex flex-m mr30">
            <yy-icon name="warning-o" size="28rpx" color="#FFB415"></yy-icon>
            <text class="ml5 fs22 fc6 line-0 fc-yellow">不支持退款</text>
          </view>
          <view class="flex flex-m">
            <yy-icon name="warning-o" size="28rpx" color="#FFB415"></yy-icon>
            <text class="ml5 fs22 fc6 line-0 fc-yellow">{{ info.purchaseQuantity | purchaseQuantity }}</text>
          </view>
        </view>
      </view>

      <view class="mt15 pay-cell border-radius-18 flex flex-m flex-b">
        <view>数量</view>
        <!--Todo @add="umChooseGoodsAmount('plus')"
        @cut="umChooseGoodsAmount('less')" -->
        <yy-stepper v-model="num" :min="1" :max="info.maxNum * 1" @clickDisabled="addDisabled" @cut="cut" />
      </view>
      <view class="border-radius-18 over-hide mt15">
        <view class="flex pay-cell pay-res-mount flex-m flex-b">
          <view>商品总额</view>
          <view class="fs30 yellow">
            <text class="fs24">¥</text>
            <text class="fs32 b">{{ needPrice | toFixed }}</text>
          </view>
        </view>
        <no-refund-agreement is-accept-type="2" ref="agree"></no-refund-agreement>
      </view>
      <view class="border-radius-18 over-hide mt15 bgfff" @click="useCoupon">
        <u-cell is-link>
          <view slot="title">
            <view class="mb20 fs30">套票立减券</view>
            <view class="fs24">{{ ticketNum }}张可用，最多省{{ ticketPrice }}元</view></view
          >
        </u-cell>
      </view>
      <view v-if="list.length > 0" class="border-radius-18 over-hide mt15 bgfff" @click="useCard">
        <u-cell is-link>
          <view slot="title">
            <view class="mb20 fs30">会员卡</view>
            <view class="fc-yellow" v-if="hasCard">-￥{{ totalPrice }}</view>
            <view v-else class="fs24">请选择会员卡，不能与套票立减券同时使用</view></view
          >
        </u-cell>
      </view>
      <!-- <footer-btn
      @click="handlePay"
      class="btn-box"
      only-btn
      btn-txt="立即购买"
    /> -->
    </view>
    <!-- <goods-pay-footer
      v-model="showMore"
      :name="info.name"
      :num="num"
      :total-price="totalPrice"
      :coupons="coupons"
      @showMore="showMore = !showMore"
      @goPay="handlePay"
    ></goods-pay-footer> -->
    <order-info-footer
      v-model="showMore"
      :ext-pay-class="extPayClass"
      :list="getList()"
      :get-need-price="needPrice"
      @showMore="showMore = !showMore"
      @goPay="handlePay"
    ></order-info-footer>
  </yy-page>
</template>

<script>
  import ProductItem from '@/pagesOrder/components/ProductItem/index.vue'
  import * as auth from '@/utils/auth'
  import judgePay from '@/mixins/judgePay.js'
  import NoRefundAgreement from '@/pagesOrder/components/NoRefundAgreement/index.vue'
  import OrderInfoFooter from '@/components/OrderInfoFooter'
  import { locPreOrderInfo, locSelGoodsCoupon, locSelCard } from '@/utils/locStore/data'
  import { toFixed } from '@/utils'
  export default {
    name: 'goods-pay',
    components: {
      ProductItem,
      NoRefundAgreement,
      OrderInfoFooter
    },
    mixins: [judgePay],
    data() {
      return {
        list: [],
        card: null,
        mallCommodityId: '',
        num: 1,
        orderType: 'mall',
        info: {},
        cardNum: 0,
        checkCardNum: 0,
        preInfo: {},
        routeQuery: {},
        showMore: false,
        coupons: []
      }
    },
    // beforeRouteEnter(to, from, next) {
    //   const noCache = ['/goodsDetail', '/orderList']
    //   handleNoCache(noCache, to, from, next)
    // },
    onLoad(options) {
      locSelGoodsCoupon.remove() //清空选券数据
      locSelCard.remove() //清空选卡数据
      this.routeQuery = options
      this.mallCommodityId = this.routeQuery.mallCommodityId
      this.query = options
      const num = this.$utils.isNaNStr(this.routeQuery.num) || 1
      this.num = num
      this.getCardNum()
    },
    onShow() {
      this.init()
    },
    computed: {
      // 卖品图标
      imageUrl() {
        const images = (this.info && this.info.image) || []
        const imgObj = images[0] || {}
        return imgObj.imageUrl
      },
      totalPrice() {
        const num = this.num
        const sellPrice = this.info.sellPrice
        const m = num * sellPrice
        return toFixed(this.$utils.isNaNStr(m))
      },
      hasCoupon() {
        if (this.coupons && this.coupons.length > 0) {
          return this.coupons[0]
        } else {
          return null
        }
      },
      hasCard() {
        console.log('hasCard', this.card)
        if (this.card) {
          return this.card
        } else {
          return null
        }
      },
      needPrice() {
        const totalPrice = this.totalPrice
        let price = this.hasCoupon ? totalPrice - this.hasCoupon.mallReduceMoney : totalPrice
        if (this.card && this.card.balance) {
          price = 0
        }
        console.log('needPrice', price)
        return price > 0 ? price : 0
      },
      zoneId() {
        return this.routeQuery.zoneId
      },
      hasInfo() {
        return this.info && this.info.canReduceCouponList
      },
      ticketNum() {
        if (this.hasInfo) {
          return this.info.canReduceCouponList && this.info.canReduceCouponList.length
        }
        return 0
      },
      ticketPrice() {
        if (this.hasInfo) {
          console.log('this.info.canReduceCouponList', this.info)
          const list = this.$utils.sortList(this.info.canReduceCouponList, 'reduceMoney')
          return list && list.length && list[0].mallReduceMoney
        }
        return 0
      }
    },

    watch: {
      num: {
        handler() {
          if (this.card && this.totalPrice > this.card.balance) {
            this.card = null
          }
        },
        immediate: true
      }
    },

    methods: {
      // 初始化方法
      init() {
        this.getInfo()
        this.getCardPay()
        this.$refs.agree && this.$refs.agree.init()
        this.coupons = locSelGoodsCoupon.get() || []
        this.card = locSelCard.get() || null
        console.log('card', this.card)
      },
      getCardNum() {
        if (this.$auth.memberSystemStatus() === '1') {
          uni.$api.memberCard
            .getMemberCardByMallCommodityId({
              mallCommodityId: this.mallCommodityId,
              cinemaId: this.$auth.getLocCinemaInfo().cinemaId
            })
            .then((res) => {
              this.list = res.list
            })
        }
      },
      getInfo() {
        const query = this.routeQuery
        const { mallCommodityId } = query
        this.$msg.loading()
        uni.$api.mall.getCommodityInfo({ mallCommodityId }).then((res) => {
          this.info = res
          this.setOwnPayList(this.info.ownPayList)
          this.$msg.hideLoading()
        })
      },
      handleSubscribe(tmplIds) {
        console.log('this.tmplIds', this.tmplIds)
        // 发起订阅
        wx.requestSubscribeMessage({
          tmplIds,
          success: (res) => {
            console.log(res, 'sub-res')
            this.createMallOrder()
          },
          fail: (err) => {
            console.log(err, 'sub-err')
            this.createMallOrder()
            // const turnArr = [20001, 20003, 20004]
            // if (turnArr.includes(+err.errCode)) {
            // } else {
            //   this.$msg.toast('网络出现问题，请重试')
            // }
          }
        })
      },
      async getTemplateIds() {
        const res = await uni.$api.public.getTemplateList({ templateType: '3' })
        this.tmplIds = res.map((item) => item)
        console.log(res)
      },
      async handlePay() {
        if (!this.$refs.agree) {
          return
        }
        if (!this.$refs.agree.feChecked) {
          return this.$refs.agree.openPopup()
        }
        // #ifndef MP-WEIXIN
        this.createMallOrder()
        // #endif
        // #ifdef MP-WEIXIN
        await this.getTemplateIds()
        wx.getSetting({
          withSubscriptions: true,
          success: (res) => {
            console.log(res, 'set-res')
            if (res.subscriptionsSetting) {
              const { mainSwitch = true } = res.subscriptionsSetting
              if (!mainSwitch) {
                this.createMallOrder()
              } else {
                this.handleSubscribe(this.tmplIds)
              }
            }
          },
          fail: (err) => {
            this.createMallOrder()
            console.log(err, 'set-err')
          }
        })
        // #endif
      },

      async createMallOrder() {
        const num = this.num
        if (num <= 0) {
          this.$msg.toast('请选择数量')
          return
        }
        const data = {
          number: num,
          mallCommodityId: this.mallCommodityId,
          zoneId: this.zoneId,
          cinemaId: this.$auth.getLocCinemaInfo().cinemaId || ''
          // cinemaId: this.routeQuery.cinemaId || ''
        }
        this.$msg.loading()
        uni.$api.mall
          .createOrder(data)
          .then((res) => {
            this.$msg.hideLoading()
            const resData = res
            const preInfo = this.createPreInfo(resData.orderId)
            const query = {
              mallOrderId: resData.orderId,
              orderType: 'mall',
              needPay: this.needPrice,
              ownPayStr: this.getOwnPayStr(),
              zoneId: this.zoneId
            }
            // auth.sLoc.set('preOrderInfo', preInfo)
            console.log('query', query)
            console.log('preInfo', preInfo)
            locPreOrderInfo.set(preInfo)
            this.$tools.navigateTo('/pagesOrder/pay/index', query)
          })
          .catch((err) => {
            console.log('err', err)
            // 商品售罄下架跳转商城首页
            if (err.status === '200004') {
              setTimeout(() => {
                auth.sLoc.set('keep', '1')
                this.$tools.navigateTo('pages/mall/mall')
              }, 1500)
            }
          })
      },

      chooseCard() {
        const query = {
          cardId: this.cardInfo.cardId,
          type: 'mall',
          prePrice: this.totalPrice,
          zoneId: this.zoneId
        }
        this.$router.push({
          path: '/movieCardList',
          query
        })
      },

      // 获取商品订单可用卡列表
      getCardPay() {
        uni.$api.mall.getCardPay().then((res) => {
          this.cardNum = res.count
        })
      },

      // 生成预下单信息
      createPreInfo(orderId) {
        const info = this.$utils.deep(this.info)
        info.num = this.num
        let preInfo = {
          orderId: orderId,
          couponId: this.hasCoupon ? this.hasCoupon.couponId : '',
          cardId: this.card ? this.card.id : '',
          // 商品消息
          goods: {
            price: this.totalPrice,
            info: info,
            discount: this.needPrice
          },
          needPay: this.needPrice
        }
        preInfo = this.$utils.deep(preInfo)
        this.preInfo = preInfo
        return preInfo
      },
      addDisabled(e) {
        console.log(e)
        if (e === 'add') {
          this.$msg.toast('商品库存不足，无法选择更多数量。')
        }
      },
      cut() {
        if (this.hasCoupon) {
          if (this.totalPrice < this.hasCoupon.mallFullMoney) {
            this.coupons = []
            locSelGoodsCoupon.remove()
          }
        }
      },
      useCoupon() {
        // this.card = null
        // locSelCard.remove()
        const query = {
          fromPage: 'sureOrder',
          totalPrice: this.totalPrice,
          mallCommodityId: this.mallCommodityId
        }
        this.$tools.navigateTo('/pagesOrder/goodsCoupon/index', query)
      },
      useCard() {
        // this.coupons = []
        // locSelGoodsCoupon.remove()
        this.$tools.navigateTo('/pagesOrder/card/index', {
          fromPage: 'goodPay',
          totalPrice: this.totalPrice,
          mallCommodityId: this.mallCommodityId,
          cinemaId: this.$auth.getLocCinemaInfo().cinemaId
        })
      },
      getList() {
        const list = []
        list.push({
          name: this.info.name + ' x ' + this.num,
          value: '￥' + this.totalPrice,
          type: '0'
        })

        this.coupons &&
          this.coupons.length > 0 &&
          this.coupons.forEach((item) => {
            list.push({
              name: item.couponName,
              value: '-￥' + item.mallReduceMoney,
              type: '0'
            })
          })
        const card = locSelCard.get() || null
        let money = 0
        if (card) {
          money = this.totalPrice
        }
        money &&
          list.push({
            name: '会员卡支付',
            value: '-￥' + money,
            type: '0'
          })
        return list
      }
      // getNeedPrice() {
      //   let totalPrice = this.totalPrice
      //   if (this.coupons && this.coupons.length > 0) {
      //     totalPrice -= this.coupons[0].mallReduceMoney
      //   }
      //   return totalPrice > 0 ? totalPrice : 0
      // }
    }
  }
</script>
<style lang="scss" scoped>
  .payList-box {
    background: #fff;
    padding-left: 0.3 * 100rpx;
    padding-right: 0.3 * 100rpx;
    box-sizing: border-box;
  }

  .goods {
    overflow: hidden;
    background: #fff;
    .top {
      // padding: 20rpx 20rpx 0;
    }
    .bottom {
      padding: 20rpx 20rpx 20rpx;
      background: lighten($color: $yellow, $amount: 40%);
    }
  }
  .aggree-cell {
    background: #fff;
    .pay-res-amount {
      padding-bottom: 30rpx;
      border-bottom: 1px solid #dedede;
    }
  }
  .pay-cell {
    font-size: 0.3 * 100rpx;
    height: 0.9 * 100rpx;
    background: #fff;
    padding-left: 0.3 * 100rpx;
    padding-right: 0.3 * 100rpx;
    box-sizing: border-box;
    &.pay-res-mount {
      border-bottom: 1px solid #f3f5f7;
    }
  }

  .goods-pay {
    height: calc(100vh - 200rpx);
    padding-bottom: 200rpx;
    &__inner {
      padding: 20rpx;
    }
  }
  .footer-btn {
    padding: 36rpx;
    // background: #fff;
  }
</style>
